#
#  Copyright 2008 Garth Williams
#
#  This file is part of CommandPost.
#
#  CommandPost is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  CommandPost is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with CommandPost.  If not, see <http://www.gnu.org/licenses/>.
#

# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  def render_text(text)
    #escape html injection, render with with textile and add wiki links
    RedCloth.new(h(text)).to_html.gsub(/\b[A-Z][a-z]+[A-Z][a-z]+\w*\b/, '<a href="/pages/\0">\0</a>')
  end
  
  def render_date(date)
    date.strftime("%A %d %B %Y")
  end
  
  def render_short_date(date)
    date.strftime("%d-%m-%Y")
  end
  
  def render_time_elapsed(date)
    now = Time.new
    minutes = ((now - date).to_i / 60).round
    if minutes < 2
      "1 minute ago"
    elsif minutes < 60
      "#{minutes} minutes ago"
    elsif date > now.beginning_of_day
      hours = minutes / 60
      if hours < 2
        '1 hour ago'
      else
        "#{hours} hours ago"
      end
    elsif date > now.yesterday.beginning_of_day
      'yesterday'
    else
      days = (minutes.to_f / 60 / 24).ceil
      if (days < 8)
        "#{days} days ago"
      else
        render_short_date(date)
      end
    end
  end
  
  def render_date_time(date)
    date.strftime("%A %d %B %Y at %H:%M")
  end

  def sidebar_content
    Page.find_by_name('sidebar_content')
  end
  
  def report_types
    if logged_in?
      current_user.report_types
    else
      Array.new
    end
  end
  
  def latest_logs
    Log.find :all, :order => 'id DESC', :limit => 5
  end
  
  def log_link(log)
    case log.subject_type
    when 'user'
      user_path(log.subject_id)
    else
      '#'
    end
  end
end
